package org.halk.es.crawl.service.impl;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.halk.es.crawl.entity.Content;
import org.halk.es.crawl.pojo.content.dto.SearchQueryContentDto;
import org.halk.es.crawl.repository.ContentRepository;
import org.halk.es.crawl.service.IndexService;
import org.halk.es.crawl.utils.HtmlParseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author halk
 * @Date 2023/3/3 10:50
 **/
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ContentRepository contentRepository;
    @Autowired
    private HtmlParseUtil htmlParseUtil;

    @Override
    public boolean parseJdSearchHtml(String keyword) throws IOException {
        ArrayList<Content> contentArrayList = htmlParseUtil.parseJD(keyword);
        this.contentRepository.saveAll(contentArrayList);
        return true;
    }

    @Override
    public List<Content> searchQuery(SearchQueryContentDto pageDto) {
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders
                .matchQuery("title", pageDto.getKeyword());
        nativeSearchQueryBuilder.withQuery(matchQueryBuilder);

        nativeSearchQueryBuilder.withPageable(PageRequest.of(pageDto.getPageNum(), pageDto.getPageSize()));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        nativeSearchQueryBuilder.withHighlightBuilder(highlightBuilder);

        Page<Content> result = this.contentRepository.search(nativeSearchQueryBuilder.build());
        List<Content> contentList = result.get().collect(Collectors.toList());
        return contentList;
    }
}
